﻿/************************************************************************
 * author:漠然 2013年7月12日4:25:15
 * 2013年7月13日16:52:33 通过在manager中通过反射实现了类型转换
 * **********************************************************************/


using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace Mrsoft.Update.Common
{
    /// <summary>
    /// 通用配置文件基础类
    /// 用来存放数据变更的主要依据
    /// </summary>
    public class Config<T>
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="fileName">文档文件存放的具体位置</param>
        /// <param name="treePath">配置的搜索路径</param>
        /// <param name="value">默认值</param>
        public Config(string fileName, string treePath, T value) {
            this.fileName = fileName;
            this.treePath = treePath;
            if (!ConfigManager.GetValue(this.fileName, this.treePath, ref value))
            {
                //不存在就将默认只保存下去
                ConfigManager.SetValue(this.fileName, this.treePath, value);
            }
            this.value = value;//赋值
        }

        #region 值的内存缓存
        private T value;
        public T Value {
            set {
                if (!this.value.Equals(value))
                {
                    this.value = value;
                    ConfigManager.SetValue(fileName, treePath, value);
                }
            }

            get {
                return value;
            }
        }
        #endregion
        
        private readonly string fileName;
        private readonly string treePath;
        public override string ToString() {
            return Value.ToString();
        }


        /// <summary>
        /// 设置控件绑定
        /// </summary>
        /// <param name="control"></param>
        /// <param name="propertyName"></param>
        public void SetBind(Control control, string propertyName) {
            ConfigFactory.BindingControlRegister(control);
            control.DataBindings.Clear();
            control.DataBindings.Add(propertyName, this, "Value", true, DataSourceUpdateMode.OnPropertyChanged);
        }
    }
}
